<template>
  <div>
    <!-- 头部-->
    <div class="address-top">
      <p @click="back">返回</p>
      <p>通讯录</p>
      <router-link :to="{ path: 'friendAdd', query:{ type: this.$route.query.type }}">添加</router-link>
    </div>
    <ul class="address-tab white">
      <li v-for="(val,key) in tabList" :class="{active:addClass===key}" @click="tabSelect(val,key)">{{val}}</li>
    </ul>
    <router-link to="/addressApply" class="flex-between notice white">
      <p class="mes"><span class="red-dot" v-show="applyMsg"></span>申请通知</p>
      <img class="img" src="../../assets/img/addressList/arrow-right.png">
    </router-link>
    <div class="blank"></div>
    <!-- 好友 -->
    <div class="address-tab-content" v-show="addClass==0">
      <div class="flex-between my-friend">
        <p>我的好友</p>
        <p>{{friendTotal}}</p>
      </div>
      <div class="flex friend-list padd15 white" v-for="(val,key) in lists" :key="key"
           @click="toFriendSession(val.Info_Account)">
        <img class="img" :onerror="defaultImg" :src="val.Tag_Profile_IM_Image?val.Tag_Profile_IM_Image:c2cHead">
        <div class="flex1 name">
          {{val.Tag_Profile_IM_Nick?val.Tag_Profile_IM_Nick:'无'}}
        </div>
      </div>
    </div>

    <!-- 群组 -->
    <div class="address-tab-content" v-show="addClass==1">
      <div class="groupWrapper">
        <router-link to="/createGroup">
          <div class="createGroup">
            <img class="img" src="../../assets/img/icon_add04@3x.png" alt="">
            创建群
          </div>
        </router-link>
        <div @click="toSendMessage(groupitem)" class="flex friend-list padd15 white" v-for="groupitem in groupListData">
          <img :onerror="defGroupImg" class="img" :src='groupitem.FaceUrl'>
          <div class="flex1 name">
            {{groupitem.Name?groupitem.Name:'无'}}
          </div>
        </div>
      </div>
    </div>
    <!-- 黑名单 -->
    <div class="address-tab-content" v-show="addClass==2">
      <div class="flex-between my-friend">
        <p>黑名单</p>
        <p>{{BlackTotal}}</p>
      </div>
      <div class="flex friend-list padd15 white" v-for="(val,key) in blackLists" :key="key"
           @click="toFriendDetails(val.To_Account)">
        <img class="img" :onerror="defaultImg" :src="val.Tag_Profile_IM_Image?val.Tag_Profile_IM_Image:defaultImg">
        <div class="flex1 name">
          {{val.Tag_Profile_IM_Nick?val.Tag_Profile_IM_Nick:'无'}}
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="less" rel="stylesheet/less" scoped>
.font16 {
  font-size: 0.16rem;
}

.color4a {
  color: #4a4a4a;
}
.fontLimit{
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
    display:block;
  }
/* 通知 */
.notice {
  height: 0.5rem;
  .mes {
    .font16;
    .color4a;
    position: relative;
    .red-dot {
      background: red;
      width: 0.05rem;
      height: 0.05rem;
      border-radius: 50%;
      display: inline-block;
      position: absolute;
      top: -0.05rem;
      left: 0.65rem;
    }
  }
  .img {
    width: 0.15rem;
  }
}
.address-tab-content {
  position: absolute;
  top: 0;
  left: 0;
  padding-top: 1.59rem;
  z-index: -1;
  box-sizing: border-box;
  height: 100%;
  width: 100%;
  overflow-y: auto;
}
.blank {
  height: 0.1rem;
  background-color: #f2f2f2;
}

/* 我的好友*/
.my-friend {
  .font16;
  .color4a;
  height: 0.4rem;
}

/* 好友列表*/
.friend-list {
  height: 0.6rem;
  align-items: center;
  .img {
    width: 0.4rem;
    height: 0.4rem;
    margin-right: 0.1rem;
    border-radius: 50%;
  }
  .name {
    border-bottom: 0.005rem solid #e1e1e1;
    height: 0.6rem;
    line-height: 0.6rem;
    .fontLimit;
    .font16;
    .color4a;
  }
}

/* 群组列表 */
.groupWrapper {
  .createGroup {
    height: 0.5rem;
    border-bottom: 1px solid #e1e1e1;
    display: flex;
    align-items: center;
    padding: 0 0.15rem;
    box-sizing: border-box;
    img {
      width: 0.15rem;
      width: 0.15rem;
      margin-right: 0.15rem;
    }
  }
}
</style>
<script>
import { checkStatus } from "../../assets/js/login";
import Client from "../../assets/js/common";
import Chat from "../../assets/js/chat";
import { Toast } from "mint-ui";
import c2cHead from '../../assets/img/my@3x.png';
export default {
  data() {
    return {
      applyMsg: false, //有无未读申请通知
      defGroupImg: Client.defaultGroupImg,
      tabList: ["好友", "群组", "黑名单"],
      lists: [], // 好友列表
      friendTotal: "", // 好友总数
      addClass: 0, // tab 样式
      blackLists: [], // 黑名单
      BlackTotal: "", // 黑名单总数
      loginInfo: {}, // 登陆信息
      groupListData: [], // 群组详情列表
      toAccount: "", // 用户id
      redDot: "", // 红点
      defaultImg: Client.defaultImg,
      c2cHead
    };
  },
  created(){
    this.initSelected(); // 当前页是否是群组页面
    checkStatus(loginInfo => {
      Chat.getAllFriend(loginInfo.identifier).then(resp => {
        if(resp == null) return;
        this.getAll(resp);
      });
      this.loginInfo = loginInfo;
      this.getGroupList(this.handleListData); // 群组列表
      //console.log('loginInfo',loginInfo);
      this.getPendency();
      this.getMsgNotify();
      this.getBlackList();
    });
  },
  mounted() {
    
  },
  methods: {
    getMsgNotify() {
      let That = this;
      webim.syncMsgs(
        resp => {
          That.getApplyJoin();
        },
        err => {
          Client.errInfo();
          //alert(err.ErrorInfo);
        }
      );
    },
    //读取好友申请列表
    getPendency() {
      let options = {
        From_Account: this.loginInfo.identifier,
        PendencyType: "Pendency_Type_ComeIn",
        StartTime: 0,
        MaxLimited: 100,
        LastSequence: 0,
        TagList: ["Tag_Profile_IM_Nick"]
      };
      webim.getPendency(
        options,
        resp => {
          console.log("好友未决", resp);
          if (resp.UnreadPendencyCount > 0) {
            this.applyMsg = true;
          }
        },
        err => {
          Client.errInfo();
          console.log(err.ErrorInfo);
        }
      );
    },
    initSelected() {
      let type = this.$route.query.type;
      if(type){
        this.addClass = +type;
      }else{
        this.addClass = 0;
      }
    },
    // tab切换
    tabSelect(val, key) {
      this.addClass = key;
      this.$router.replace({ path: "AddressList", query: { type: key } });
    },
    // 返回
    back() {
      this.$router.push("/");
    },
    // 查看好友详情
    toFriendDetails(account) {

      this.$router.push({ path: "friendDetails", query: { id: account } });
    },
    // 好友聊天
    toFriendSession(account) {
      this.$router.push({ path: "session", query: { id: account,selType:'C2C' } });
    },
    // 获取全部好友
    getAll(resp) {
      for (let i = 0; i < resp.InfoItem.length; i++) {
        if (resp.InfoItem[i].SnsProfileItem) {
          let sns = resp.InfoItem[i].SnsProfileItem;
          sns.forEach((ele, index) => {
            resp.InfoItem[i][ele.Tag] = ele.Value;
          });
          resp.InfoItem[i]["To_Account"] = resp.InfoItem[i]["Info_Account"]; // 用户ID 统一为  To_Account
          // 删除属性
          delete resp.InfoItem[i].SnsProfileItem;
        }
      }
      this.lists = resp.InfoItem;
      //console.log('this.lists',this.lists);
      this.friendTotal = this.lists.length;
    },
    // 我的黑名单
    getBlackList(cbOK, cbErr) {
      let options = {
        From_Account: this.loginInfo.identifier,
        StartIndex: 0,
        MaxLimited: 100,
        LastSequence: 0
      };

      webim.getBlackList(
        options,
        resp => {
          /* 黑名单接口只有账号 To_Account ,再利用账号查找详情信息..*/
          if (resp.BlackListItem && resp.BlackListItem.length > 0) {
            this.BlackTotal = resp.BlackListItem.length;
            let arr = [];
            for (let i = 0; i < resp.BlackListItem.length; i++) {
              arr.push(resp.BlackListItem[i].To_Account);
            }
            this.getProfile(arr);
          }
        },
        err => {
          Client.errInfo();
          //alert(err.ErrorInfo);
        }
      );
    },
    //获取用户个人资料
    getProfile(arr) {
      let tag_list = [
        "Tag_Profile_IM_Nick", //昵称
        "Tag_Profile_IM_Gender", //性别
        "Tag_Profile_IM_AllowType", //加好友方式
        "Tag_Profile_IM_Image" //头像
      ];
      let objs = {
        To_Account: arr,
        TagList: tag_list
      };
      webim.getProfilePortrait(
        objs,
        resp => {
          if (resp.UserProfileItem && resp.UserProfileItem.length > 0) {
            for (let i = 0; i < resp.UserProfileItem.length; i++) {
              if (resp.UserProfileItem[i].ProfileItem) {
                let sonItem = resp.UserProfileItem[i].ProfileItem;
                sonItem.forEach((ele, index) => {
                  resp.UserProfileItem[i][ele.Tag] = ele.Value;
                });
                delete resp.UserProfileItem[i].ProfileItem; // 删除属性
              }
            }
            this.blackLists = resp.UserProfileItem;
          }
        },
        err => {
          Client.errInfo();
          //alert(err.ErrorInfo);
        }
      );
    },

    // group-start-------------------------------------------------
    // ------------------------------------------------------------
    // ------------------------------------------------------------

    //
    getApplyJoin() {
      let arr = this.loginInfo.onApplyJoinGroupRequestNotify;
      if (arr && arr.length > 0) {
        this.applyMsg = true;
      }
    },
    // 群组列表
    getGroupList(cbOK) {
      let options = {
        Member_Account: this.loginInfo.identifier,
        Limit: 200,
        Offset: 0,
        //'GroupType':'',
        GroupBaseInfoFilter: [
          "Type",
          "Name",
          "Introduction",
          "Notification",
          "FaceUrl",
          "CreateTime",
          "Owner_Account",
          "LastInfoTime",
          "LastMsgTime",
          "NextMsgSeq",
          "MemberNum",
          "MaxMemberNum",
          "ApplyJoinOption",
          "ShutUpAllMember"
        ],
        SelfInfoFilter: ["Role", "JoinTime", "MsgFlag", "UnreadMsgNum"]
      };
      webim.getJoinedGroupListHigh(
        options,
        function(resp) {
          if (!resp.GroupIdList || resp.GroupIdList.length == 0) {
            // Toast({
            //   message: '你目前还没有加入任何群组',
            //   position: 'bottom',
            //   duration: 3000
            // });
            return;
          }
          if (cbOK) {
            cbOK(resp);
          }
        },
        function(err) {
          Client.errInfo();
          //alert(err.ErrorInfo);
        }
      );
    },

    // 处理群组列表数据
    handleListData(resp) {
      for (let i = 0; i < resp.GroupIdList.length; i++) {
        let groupId = resp.GroupIdList[i].GroupId;
        let data = {
          GId: groupId,
          GroupId: webim.Tool.formatText2Html(groupId),
          Name: webim.Tool.formatText2Html(resp.GroupIdList[i].Name),
          FaceUrl: resp.GroupIdList[i].FaceUrl,
          TypeEn: resp.GroupIdList[i].Type,
          Type: webim.Tool.groupTypeEn2Ch(resp.GroupIdList[i].Type),
          RoleEn: resp.GroupIdList[i].SelfInfo.Role,
          Role: webim.Tool.groupRoleEn2Ch(resp.GroupIdList[i].SelfInfo.Role),
          MsgFlagEn: resp.GroupIdList[i].SelfInfo.MsgFlag,
          MsgFlag: webim.Tool.groupMsgFlagEn2Ch(
            resp.GroupIdList[i].SelfInfo.MsgFlag
          ),
          MemberNum: resp.GroupIdList[i].MemberNum,
          Notification: webim.Tool.formatText2Html(
            resp.GroupIdList[i].Notification
          ),
          Introduction: webim.Tool.formatText2Html(
            resp.GroupIdList[i].Introduction
          ),
          JoinTime: webim.Tool.formatTimeStamp(
            resp.GroupIdList[i].SelfInfo.JoinTime
          ),
          ShutUpAllMember: resp.GroupIdList[i].ShutUpAllMember,
          SelfInfo: resp.GroupIdList[i].SelfInfo
        };
        this.groupListData.push(data);
      }
      console.log("28b", this.groupListData);
    },

    toSendMessage(data) {
      this.$router.push({
        path: "/session",
        query: { selType: "GROUP", id: data.GroupId }
      });
    }
    // group-end
  },
  watch: {
    // 资料变化
    "loginInfo.onProfileModifyNotify":function(val) {
      if(!val) return;
      Chat.getAllFriend(this.loginInfo.identifier).then(resp => {
        if(resp == null) return;
        this.getAll(resp);
      });
    },
    // 好友申请监听
    "loginInfo.onPendencyAddNotify": function(val) {
      if (val && val.PendencyList) {
        this.applyMsg = true;
      }
    },
    // 监听 申请加群被同意 系统消息
    /*"loginInfo.onApplyJoinGroupAcceptNotify": function (val, oldval) {
        if (!val.length) return
        console.log('申请加群被同意', val);
        this.redDot = !!val.length
      },
      // 监听 被踢 系统消息
      "loginInfo.onKickedGroupNotify": function (val, oldval) {
        if (!val.length) return
        this.redDot = !!val.length
      },*/
    "loginInfo.onApplyJoinGroupRequestNotify": function(val, oldval) {
      if (val.length > 0) {
        this.applyMsg = true;
      }
    },
    "loginInfo.onFriendAddNotify":function(val){
        if(val&&val.Type == 1){
          Chat.getAllFriend(this.loginInfo.identifier).then(resp => {
            if(resp == null) return;
            this.getAll(resp);
          });
        }
    }
  }
};
</script>
